<?php
function validate($billing_fields=array(),$account_fields=array()) {
	$ci =& get_instance();
	#get fields value
	#billing fields
	$fname	= $billing_fields['fname'];
	$lname	= $billing_fields['lname'];
	$add1	= $billing_fields['add1'];
	$city	= $billing_fields['city'];
	$phone	= $billing_fields['phone'];
	$email	= $billing_fields['email'];
	$countryId	= $billing_fields['countryId'];
	$stateId	= $billing_fields['stateId'];
	$zip		= $billing_fields['zip'];
	#account fields
	$create_acc	= $account_fields['create_acc'];
	$username	= $account_fields['username'];
	$pass		= $account_fields['pass'];
	$pass2		= $account_fields['pass2'];
	
	#validate billing info
	$errors = array();
	#validate first name
	if($fname=='' || preg_match("/[0-9]/", $fname)) {
		$errors['fname'] = 1;	
	}else $errors['fname'] = 0;
	
	#validate last name
	if($lname=='' || preg_match("/[0-9]/", $lname)) {
		$errors['lname'] = 1;	
	}else $errors['lname'] = 0;
	
	#validate address1
	$errors['add1']	 	= ($add1=='')?1:0;
	#validate city
	$errors['city']		= ($city=='')?1:0;
	#validate phone
	$errors['phone']	= ($phone=='')?1:0;
	#validate email
	$ci->load->helper('validate_email');
	$errors['email']	= check_email_address($email);
	
	#validate state and zip
	$ci->load->model('country/country_model','country_model');
	$country = $ci->country_model->getCountryDetail($countryId);
	
	#validate state
	#get list of states
	$states = $ci->country_model->getStateOfCountry($countryId);
	if(count($states)>0) {
		$errors['state'] = ($stateId=='')?1:0;	
		#get state detail
		if($errors['state']==0) { 
			$state 		= $ci->country_model->getStateDetail($stateId);
			$state_name = $state->state_name;
		} else $state_name = '';
	} else {
		$errors['state'] = ($stateId=='')?2:0;
		$state_name	= $stateId;
	}
	
	#validate zip code
	if($country->country_name == 'United States') {
		$reg = "/^\d{5}(-\d{4})?$/";
		$errors['zip'] = (preg_match($reg,$zip))?0:1;
	} else if($country->country_name == 'Canada') {
		$reg = "/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/";
		$errors['zip'] = (preg_match($reg,$zip))?0:2;
	} else {
		$errors['zip'] = ($zip=='')?2:0;
	}
	
	#validate account fields
	if($create_acc == 1) {
		#validate username
		if(!preg_match("/^[\w\d\._]{4,31}$/", $username)) {
			$errors['username'] = 1;	
		}else $errors['username'] = 0;
		
		#validate password
		$errors['pass']	= (strlen($pass)<6)?1:0;
		#validate password 2
		$errors['pass2'] = (!$errors['pass'] && $pass2 != $pass)?1:0;
		#validate email
		if($errors['email']==0) {
			$ci->load->model('user/user_model','user_model');
			$errors['email'] = ($ci->user_model->checkDuplicatedEmail($email))?2:0;
		}
	}
	
	$error = 0;
	foreach($errors as $e) $error += $e;
	
	$result = array(
		'error'		=> $error,
		'errors'	=> $errors,
		'country'	=> $country,
		'state_name'=> $state_name
	);
	return $result;
}